<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\controller\room;


use app\adminapi\controller\BaseAdminController;
use app\adminapi\lists\room\RoomApartmentLists;
use app\adminapi\lists\room\RoomApartmentUserLists;
use app\adminapi\logic\room\RoomApartmentLogic;
use app\adminapi\validate\room\RoomApartmentValidate;
use app\common\model\Building;
use app\common\model\Campus;
use app\common\model\room\RoomApartment;
use app\common\model\room\RoomApartmentDevice;
use app\common\model\room\RoomApartmentDeviceLog;
use app\common\model\room\RoomApartmentLog;
use app\common\model\room\RoomApartmentUser;
use app\common\model\room\RoomApartmentUserRecords;
use think\Db;


/**
 * 公寓房间管理控制器
 * Class RoomApartmentController
 * @package app\adminapi\controller\room
 */
class RoomApartmentController extends BaseAdminController {


    /**
     * @notes 获取公寓房间管理列表
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function lists() {
        return $this->dataLists(new RoomApartmentLists());
    }

    public function searchLists() {
        $month_list = [];
        $max_y = date("Y");
        $max_m = 12;
        for ($y = 2024; $y <= $max_y; $y++) {
            if ($y == $max_y) {
                $max_m = date("m");
            }
            for ($m = 1; $m <= $max_m; $m++) {
                if ($m < 10) {
                    $month_list[$y . 0 . $m] = [
                        "name" => $y . '年' . 0 . $m . '月',
                        "id" => $y . 0 . $m,
                    ];
                } else {
                    $month_list[$y . $m] = [
                        "name" => $y . '年' . $m . '月',
                        "id" => $y . $m,
                    ];
                }
            }
        }

        $cid = $this->adminCid;

        $c_where = [];
        $c_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $c_where[] = ["id", "=", $cid];
        }

        $b_where = [];
        $b_where[] = ["status", "=", 1];
        if ($cid !== 0) {
            $b_where[] = ["cid", "=", $cid];
        }

        return $this->success('', [
            "month_list" => array_reverse($month_list),
            "campus_list" => Campus::where($c_where)->select()->toArray(),
            "building_list" => Building::where($b_where)->select()->toArray(),
            "cb_lists" => Campus::field([
                "id", "name",
                "id as value",
                "name as label",
            ])->where($c_where)->with(["building" => function ($q) use ($b_where) {
                $q->field([
                    "id", "name", "cid", "id as value", "name as label",
                ])->where($b_where);
            }])->select()->each(function ($item) {
                $item->children = $item['building'];
                unset($item['building']);
                return $item;
            })->toArray(),
            "type_list" => RoomApartment::getTypeList(),
            "lift_list" => RoomApartment::getLiftList(),
            "pkl_room" => RoomApartment::getPrintKeywordListRoom(),
        ], 1, 1);
    }


    /**
     * @notes 添加公寓房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function add() {
        $params = (new RoomApartmentValidate())->post()->goCheck('add');
        $result = RoomApartmentLogic::add($params);
        if (true === $result) {
            return $this->success('添加成功', [], 1, 1);
        }
        return $this->fail(RoomApartmentLogic::getError());
    }


    /**
     * @notes 编辑公寓房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function edit() {
        $params = (new RoomApartmentValidate())->post()->goCheck('edit');
        $result = RoomApartmentLogic::edit($params);
        if (true === $result) {
            return $this->success('编辑成功', [], 1, 1);
        }
        return $this->fail(RoomApartmentLogic::getError());
    }

    public function setSave() {
        $params = $this->request->param();
        $res = RoomApartmentLogic::setSave($params);
        if (!$res) {
            return $this->fail(RoomApartmentLogic::getError());
        }
        return $this->success('编辑成功', [], 1, 1);
    }

    /**
     * @notes 删除公寓房间管理
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function delete() {
        $params = (new RoomApartmentValidate())->post()->goCheck('delete');
        RoomApartmentLogic::delete($params);
        return $this->success('删除成功', [], 1, 1);
    }


    /**
     * @notes 获取公寓房间管理详情
     * @return \think\response\Json
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function detail() {
        $params = (new RoomApartmentValidate())->goCheck('detail');
        $result = RoomApartmentLogic::detail($params);
        return $this->data($result);
    }

    /**
     * @notes 获取公寓房间更新费用
     */
    public function updateFee() {
        $blist = Building::where([
            ["status", "=", "1"],
        ])->where(function ($query) {
            $query->whereOr([
                ["all_lift_fee", ">", "0"],
                ["all_second_pressure_fee", ">", "0"],
            ]);
        })->select()->toArray();

        $db = new Db();
        $bids = [];
        foreach ($blist as $v) {
            $rh_ids = RoomApartment::where("status", 1)->where("bid", $v['id'])->whereNotIn("type", [0])->column("id");
            $all_lift_type = RoomApartment::where("status", 1)->where("bid", $v['id'])->whereNotIn("type", [0])->sum('lift_type');
            RoomApartment::whereIn("id", $rh_ids)->where("bid", $v['id'])->whereNotIn("type", [0])->update([
                "second_pressure_fee" => $db->raw($v['all_second_pressure_fee'] . "/" . count($rh_ids)),
                "lift_fee" => $db->raw("lift_type/" . $all_lift_type . "*" . $v['all_lift_fee']),
            ]);
            $bids[] = $v['id'];
        }
        Building::whereIn("id", $bids)->update([
            "is_month_begin" => 1,
        ]);
        return $this->data($blist);
    }


    /**
     * @notes 公寓房间月初始化
     */
    public function newMonth() {
        set_time_limit(30000);
        ini_set("max_execution_time", 30000);

        $data = [
            "ym" => date("Ym"),
//            "ym" => 202404,
            "this_time" => date("Y-m-d H:i:s"),
//            "this_time" => date("2024-04-28 H:i:s"),
            "db" => new Db(),
        ];

//        // 设备数据清空
//        RoomApartmentDevice::where([
//            ["status", "=", 1],
//        ])->update([
////            "base_number" => 0,
//            "reading" => $data["db"]->raw("reading + rand() * 100"),
//            "update_time" => date("Y-m-d H:i:s"),
////            "use_total" => $data["db"]->raw("(reading - base_number)"),
////            "total_fee" => $data["db"]->raw("(reading - base_number) * coefficient * price"),
////            "log_time" => date("Y-m-d H:i:s"),
////            "lift_fee" => 0, // 电梯费
////            "second_pressure_fee" => 0, // 二次压力费
//        ]);
//        var_dump("ceshi------------------");exit;

//        // 设备数据清空
//        RoomApartmentDevice::where([
//            ["status", "=", 1],
//        ])->update([
////            "base_number" => $data["db"]->raw("reading"),
////            "reading" => $data["db"]->raw("reading + rand() * 100"),
//            "update_time" => date("Y-m-d H:i:s"),
//            "use_total" => $data["db"]->raw("(reading - base_number)"),
//            "total_fee" => $data["db"]->raw("(reading - base_number) * coefficient * price"),
//            "log_time" => date("Y-m-d H:i:s"),
////            "lift_fee" => 0, // 电梯费
////            "second_pressure_fee" => 0, // 二次压力费
//        ]);
//        var_dump("ceshi------------------");
//        exit;

        // 住户数据统计并记录
        $where = [];
        $room_user_save = RoomApartmentUserRecords::field([
            'room_apartment_id', // with查询数据
            "'" . $data['this_time'] . "' as add_time", "'" . $data['this_time'] . "' as log_time", "'" . $data['ym'] . "' as log_date",
            'user_id', 'user_name', 'user_mobile', "GROUP_CONCAT(room_apartment_id) as room_ids",
        ])->where($where)->with([
            "allRoomStat",
        ])->group('user_id')->select()->toArray();
        $room_user_save = (new RoomApartmentUserRecords())->data_append($room_user_save);
        (new RoomApartmentUser())->saveAll($room_user_save);
//        var_dump($room_user_save);exit;

        // 房间数据统计并记录
        $room_log_save = RoomApartment::field([
            "*", "'" . $data['this_time'] . "' as log_time", "'" . $data['ym'] . "' as log_date", "'true' as no_append",
            "id as rid", "lift_fee as room_lift_fee", "second_pressure_fee as room_second_pressure_fee",
        ])
            ->where([
                ["status", "=", 1],
            ])
            ->with([
                "campus", "building", "user",
            ])
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_s_use_total';
                $query->where('device_type', 1);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_s_price';
                $query->where('device_type', 1);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_s_total_fee';
                $query->where('device_type', 1);
            }], "total_fee")
            ->withCount(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_s_device_count';
                $query->where('device_type', 1);
            }])
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_d_use_total';
                $query->where('device_type', 2);
            }], "use_total")
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_d_price';
                $query->where('device_type', 2);
            }], "price")
            ->withSum(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_d_total_fee';
                $query->where('device_type', 2);
            }], "total_fee")
            ->withCount(["allDevice" => function ($query, &$alias) use ($data) {
                $alias = 'room_d_device_count';
                $query->where('device_type', 2);
            }])
            ->select()->each(function (&$item) {
                $item->cname = $item['campus'] ? $item['campus']['name'] : '';
                $item->bname = $item['building'] ? $item['building']['name'] : '';

                $item->room_s_device_count = $item->room_s_device_count + ($item['water_fee'] > 0 ? 1 : 0);
                $item->room_s_use_total = sprintf("%.2f", array_sum([
                    $item['room_s_use_total'], $item['water_consumption'],
                ]));
                $item->room_s_price = sprintf("%.6f", ($item['room_s_price'] + $item['water_price']) / $item['room_s_device_count']);
                $item->room_s_total_fee = sprintf("%.6f", array_sum([
                    $item['room_s_total_fee'], $item['water_fee'],
                ]));

                $item->room_d_use_total = $item['room_d_use_total'] * 1;
                $item->room_d_price = $item['room_d_price'] / ($item['room_d_device_count'] * 1 <= 0 ? 1 : $item['room_d_device_count']);
                $item->room_d_total_fee = $item['room_d_total_fee'] * 1;

                $item->room_all_total_fee = sprintf("%.6f", array_sum([
                    $item['room_lift_fee'], $item['room_second_pressure_fee'], $item['room_s_total_fee'], $item['room_d_total_fee'],
                ]));

                $item->user = json_encode($item['user'], JSON_UNESCAPED_UNICODE);
                unset($item['id']);
                return $item;
            })->toArray();
        (new RoomApartmentLog())->saveAll($room_log_save);
//        var_dump($room_log_save);exit;


        // 设备数据统计并记录
        $device_log_save = RoomApartmentDevice::field([
            "*", "log_time as reading_time", "id as log_id",
        ])->with([
            "room",
        ])->select()->each(function ($item) use ($data) {
            $item->user_ids = implode(",", $item['room']['user_ids']);
            $item->user_count = $item['room']['user_count'];
            $item->log_date = $data['ym'];

            unset($item['id']);
            return $item;
        })->toArray();
        $device_log_save = array_map(function ($item) use ($data) {
            $item['log_time'] = $data['this_time'];
            return $item;
        }, $device_log_save);
        (new RoomApartmentDeviceLog())->saveAll($device_log_save); // ->strict(false)
//        var_dump($device_log_save);exit;


        // 设备数据清空
        RoomApartmentDevice::where([
            ["status", "=", 1],
        ])->update([
            "base_number" => $data["db"]->raw("reading"),
            "use_total" => 0,
            "total_fee" => 0,
            "log_time" => null,
            "update_time" => date("Y-m-d H:i:s"),
            "lift_fee" => 0, // 电梯费
            "second_pressure_fee" => 0, // 二次压力费
        ]);


        // 房间数据清空
        RoomApartment::where([
            ["status", "=", 1],
        ])->update([
            "lift_fee" => 0, // 电梯费
            "second_pressure_fee" => 0, // 二次压力费
            "update_time" => date("Y-m-d H:i:s"),
        ]);


        return $this->success('操作成功', [], 1, 1);
    }


}

